<?php
require_once dirname(__FILE__) . '/common.inc.php';

if (isset($_COOKIE[USER])) {
  $_SESSION[USER] = json_decode($_COOKIE[USER]);
}

$template = MiscUtils::getParam('t', 'signin');
$options = MiscUtils::getParam('opts', json_encode(array()));
$base = MiscUtils::getParam('b', 'base');

$smarty->assign('p', 'admin/');
$smarty->assign('u', json_encode(array()));
$smarty->assign('d', json_encode(array()));
$smarty->assign('opts', json_encode(array()));
$smarty->assign('msg', json_encode(array()));

$logout = MiscUtils::getParam('logout', NULL);
if ($logout === '') {
  unset($_SESSION[USER]);
  setcookie(USER, '', time() - 1, PATH, DOMAIN);
  $smarty->assign('t', 'signin');
  $smarty->display("admin/gui/baseblank.tpl");
  return; /* SignOut */
}

if (isset($_SESSION[USER])) {
  if ($template == 'signin') {
    $template = 'pages';
  }
  $smarty->assign('user', $_SESSION[USER]);
  $smarty->assign('t', "$template");
  $smarty->assign('u', json_encode($_SESSION[USER]));
  $smarty->assign('d', time());
  $smarty->assign('opts', urldecode($options));
  loadPage($template);
  $smarty->display("custom/admin/gui/baseblank.tpl");
  return;
} else {
  $smarty->assign('t', 'signin');
  $smarty->display("custom/admin/gui/baseblank.tpl");
  return; /* SignIn Required */
}

function loadPage($template) {
  $message = array();
  
  switch ($template) {
    case 'knowledges':
      knowledges($message);
      break;
    case 'knowledge':
      knowledge($message);
      break;
    default:
      header('Location: http://' . DOMAIN . PATH);
      break;
  }
}

function knowledges($message) {
  global $smarty;
  $message['k'] = DbUtils::get(DbUtils::createPdoInst(), 'pz_knowledge', NULL, NULL, NULL, NULL, NULL, NULL)->d;
  $smarty->assign('msg', json_encode($message));
}

function knowledge($message) {
  global $smarty;
  $id = MiscUtils::getParam('i', NULL);
  if ($id) {
    $cond_vals = new stdClass();
    $cond_vals->c = 't.id = ?';
    $cond_vals->v = array($id);
    $message[0] = DbUtils::get(DbUtils::createPdoInst(), 'pz_knowledge', $cond_vals, NULL, NULL, NULL, NULL, NULL);
    $message['i'] = $id;
    $smarty->assign('msg', json_encode($message));
  }
}
?>